package com.aruba.attendance.initial.view

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavHostController
import com.aruba.attendance.R
import com.aruba.attendance.initial.viewmodel.InitialViewModel
import com.aruba.attendance.ui.widget.loading.LoadingContent
import com.aruba.attendance.ui.widget.loading.enums.LoadingState
import kotlinx.coroutines.launch

/**
 * 时间选择
 * Created by aruba on 2023/3/10.
 */
@Composable
fun InitialTimeSelect(
    initialViewModel: InitialViewModel,
    navController: NavHostController? = null,
    hintContent: @Composable (ColumnScope.() -> Unit)? = null
) {
    val animateLoading: MutableState<LoadingState> =
        remember { mutableStateOf(LoadingState.Normal) }

    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        val hostState by remember { mutableStateOf(SnackbarHostState()) }
        val scope = rememberCoroutineScope()

        TimeSelectView(
            initialStartTime = initialViewModel.startTime,
            initialEndTime = initialViewModel.endTime,
            timeSelect = { startTime, endTime ->
                initialViewModel.saveWorkTime(startTime, endTime) { state ->
                    animateLoading.value = state
                    if (state is LoadingState.Error) {
                        scope.launch {
                            hostState.showSnackbar(state.msg)
                        }
                    }
                }
            },
            buttonContent = {
                LoadingContent(
                    loadingState = animateLoading,
                    defaultContent = { Text(text = stringResource(R.string.sure)) },
                    animFinishCallback = {
                        // 改变状态为已配置，进而发生重组
                        initialViewModel.configComplete()
                        // 处于设置时，返回日历界面
                        navController?.popBackStack()
                    }
                )
            },
            hintContent = hintContent
        )

        SnackbarHost(hostState = hostState, modifier = Modifier.align(Alignment.BottomCenter))
    }
}